from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from  rest_framework import  status
from rest_framework.views import APIView
from datetime import datetime

from app.models import Scheduling,Activity
from app.serializers import ShedulingSerializer


class SchedulingViewSet(viewsets.ModelViewSet):
    queryset = Scheduling.objects.all()
    serializer_class = ShedulingSerializer

    @action(detail=False, methods=['post'])
    def bulk_create(self, request, *args, **kwargs):
        data = request.data  # 假设请求体是一个列表形式的数据，例如 [{"name": "item1", "description": "desc1"}, ...]
        serializer = ShedulingSerializer(data=data, many=True)  # 设置many=True以处理多个对象
        if serializer.is_valid():
            serializer.save()  # 保存所有对象到数据库中
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, instance):
        Scheduling.objects.filter(id=instance.id).delete()
        response = {
            'status': 'success',
            'code': 200,
            'msg':'删除成功'
        }
        return Response(response, status=status.HTTP_204_NO_CONTENT)
   #通过日期查找
    @action(detail=False, methods=['get'])
    def list_by_date(self, request, *args, **kwargs):
        params=request.query_params;
        date=params.get('date') + " 00:00:00"
        activity_id=params.get('activity_id')
        activity_object=Activity.objects.filter(id=activity_id).values()

        current_activity=activity_object[0]
        start_time = current_activity['start_time'].strftime("%Y-%m-%d %H:%M:%S")
        end_time = current_activity['end_time'].strftime("%Y-%m-%d %H:%M:%S")
        if current_activity:
           flag=self.is_time_in_range(start_time,end_time,date)
           if flag:
             scheduling_list= self.list_by_activity(activity_id)
             # total=scheduling_list.count()
             # response = {
             #     'status': 'success',
             #     'code': 200,
             #     'message': '返回成功',
             #     'data': scheduling_list,
             #     'total': total
             # }
             return Response(scheduling_list, status=status.HTTP_200_OK)
    #判断时间是否在某段时间内
    def is_time_in_range(self,start_time_str, end_time_str, check_time_str):
        start_time = datetime.strptime(start_time_str, '%Y-%m-%d %H:%M:%S')
        end_time = datetime.strptime(end_time_str, '%Y-%m-%d %H:%M:%S')
        check_time = datetime.strptime(check_time_str, '%Y-%m-%d %H:%M:%S')
        if start_time <= check_time <= end_time:
            return True
        else:
            return False

    def list_by_activity(self, activity_id):
        scheduling_list=Scheduling.objects.filter(activity_id=activity_id)
        print('activity_object',scheduling_list)
        return scheduling_list.values()











